    //
    //  LiveViewController.m
    //  penzer
    //
    //  Created by caiyc on 2018/9/18.
    //  Copyright © 2018年 caiyc. All rights reserved.
    //

    #import "LiveViewController.h"
    #import "pop_func.h"
    #import "pop_goodView.h"
    #import "hostPopFunc.h"
    #import "Dnmu_Cell.h"
    #import <BDCloudMediaPlayer/BDCloudMediaPlayerController.h>
    #import <BDCloudAVKit/BDCloudAVLiveSession.h>
    #import "Result_popView.h"
    #import <BDCloudAVKit/BDCloudAVReplayKitLiveSession.h>
    //#import "Regist2ViewController.h"
    #import "EndLiveViewController.h"
    #import <GPUImage/GPUImageView.h>
    #import <GPUImage/GPUImageBilateralFilter.h>
    #import <GPUImage/GPUImageBrightnessFilter.h>
    #import <GPUImage/GPUImageVideoCamera.h>
    #import <BDCloudAVFilters/BDCloudAVNaturalBeautyFilter.h>
    #import "TagView.h"
    #import "ActiveTag.h"
    #import "DXAlertView.h"
    #import "DanmuCell.h"
    #import "SRWebSocket.h"
    #import "C_SocketUtility.h"
    #import "JFRWebSocket.h"
    #import <BDCloudAVBidirectRTMPKit/BDCloudAVBidirectRTMPKit.h>

    static NSString * const kAccessKey = @"8643cf93d7fa4cf7897b10a7191ca73d";//8643cf93d7fa4cf7897b10a7191ca73d    //36a33862f54f47029ea0a3caedef3b3a
    static NSString * const kSecretKey = @"7289921dd22e45139865d9374131c8d1";
    static NSString * const kUserId = @"aa53433ed94c41cea1f3bb7168791006";
    static NSString *const WeixinAppid = @"wx130fbddb55a30f80";

    @interface LiveViewController ()<MBProgressHUDDelegate,BDCloudAVLiveSessionDelegate,PopfunsDelegate,PopfuncDelegate,UITableViewDelegate,UITableViewDataSource,TagViewDelegate,A_TagViewDelegate,DXAlertViewDelegate,BDCloudAVLiveSessionDelegate,ResultPopDelegate,SRWebSocketDelegate,JFRWebSocketDelegate,AVAudioRecorderDelegate,AVCaptureVideoDataOutputSampleBufferDelegate>
{
    dispatch_queue_t _videoBufferQueue;
}
    //@property(nonatomic,strong)BDCloudAVLiveSession *player;

  //  @property(nonatomic,strong)BDCloudAVLiveSession*session;
@property(nonatomic,strong)BDCloudAVLiveSession*session;
@property(nonatomic,strong)BDCloudAVRecordSession *recordSession;
    //@property(nonatomic,strong)BDCloudAVBidirectRTMPSession*session;
    @property(nonatomic,strong)BDCloudAVReplayKitLiveSession *repeateSession;//录屏的直播流
    @property(assign)NSInteger rewad_Num;//本场活动的中奖数字
    @property(assign)NSInteger cutdown_time;//抢购开始的时间
    @property(assign)NSInteger end_time;//活动结束时间
    @property(assign)NSInteger startlive_time;//开始直播的时间
    @property(nonatomic,strong)UILabel *time_lab1;
    @property(nonatomic,strong)UILabel *time_lab2;
    @property(nonatomic,strong)UILabel *time_lab3;
    @property(nonatomic,strong)UILabel *time_lab4;
    @property(nonatomic,strong)UIImageView *like_image;
    @property(nonatomic,strong)UIButton *random_Btn;
    @property(nonatomic,strong)NSTimer *rand_Timer;
    @property (nonatomic ,strong)dispatch_source_t timer;
    @property(assign)BOOL isrobing;//是否已经在抢购
    @property(nonatomic,strong)NSString *bdlive_Url;
    @property(nonatomic,strong)MBProgressHUD *HUD;
    @property(assign)BOOL isstart;//是否可以直播
    @property(assign)BOOL isrepeate;//是否开启录屏
    @property(nonatomic,strong)UIView *result_view;
    @property(nonatomic,strong)UIView *bottomControlView;
    @property (nonatomic, weak)GPUImageBilateralFilter  *bilateralFilter;
    @property (nonatomic, weak)GPUImageBrightnessFilter *brightnessFilter;
    @property (nonatomic, strong)GPUImageVideoCamera *videoCamera;
    @property(nonatomic,strong)BDCloudAVNaturalBeautyFilter *beautyFilter;
    @property(nonatomic,strong)UIView * diagAlertView;//开播前的确认操作视图
    @property(assign)BOOL danmustatus;//弹幕s状态
    @property(assign)BOOL iscollect;//是否收藏直播间
    @property(nonatomic,strong)UITableView *left_tab;
    @property(nonatomic,strong)NSMutableArray *newsComent;//存放弹幕的数组
    @property(nonatomic,strong)UIView *hostInfoView;//主播信息的视图
    @property(nonatomic,strong)UIView *active_View;//
    @property(nonatomic,strong)NSMutableArray *dataSource;
    @property(nonatomic,strong)UIScrollView *active_ScroView;
    @property(assign)NSInteger Dampage;
    @property(assign)BOOL openDm;
    @property(nonatomic,strong)NSDictionary *live_Detail;
    @property(nonatomic,strong)NSString *active_TIme;//活动时长
    @property(nonatomic,strong)NSString *goodId;//选择活动的商品
    @property(nonatomic,strong)UIView *filter_View;//特效view
    @property(assign)BOOL is_start;//开始直播
    @property(nonatomic,strong)UILabel *dayLb;
    @property(nonatomic,strong)UILabel *day_Des;
    @property(nonatomic,strong)UILabel *HouseLb1;
    @property(nonatomic,strong)UILabel *HouseLb2;
    @property(nonatomic,strong)NSMutableArray *select_BtnArr;
    @property(nonatomic,strong)NSMutableArray *goodsList;
    @property(assign)NSInteger selectGoodIdx;
    @property(assign)BOOL camerapostion;//摄像头位置
    @property(nonatomic,strong)UIView *activeTimeView;//抢购倒计时的view
    @property(assign)NSInteger activeTime;
    @property(assign)BOOL openActive;
    //@property(nonatomic,strong)SRWebSocket *socket;
    @property(nonatomic,strong)JFRWebSocket *socket;
    @property(assign)NSInteger coutHart;
    @property(nonatomic,strong)UIImageView *StoreIcon;
    @property(nonatomic,strong)UILabel *likeNum;
    @property(nonatomic,strong)UIView *endpopView;
    @property(nonatomic,strong)UIView *active_TimeView;

    @property(nonatomic,strong)UILabel *activeTime1;
    @property(nonatomic,strong)UILabel *activeTime2;
    @property(nonatomic,strong)UILabel *activeTime3;
    @property(nonatomic,strong)UILabel *activeTime4;
@property(nonatomic,strong)AVAudioRecorder*recorder;
@property(nonatomic,strong)NSURL *urlPlay;
@property(nonatomic,strong)AVPlayer *Audioplayer;
@property(nonatomic,strong)AVAudioSession *Audionsession;
@property(nonatomic,strong)BDCloudAVCaptureOutput *capturer;
@property(nonatomic,strong)AVCaptureDeviceInput *deviceInput;
@property(nonatomic,strong)AVCaptureStillImageOutput *imageOutput;
@property(nonatomic,strong)AVCaptureVideoDataOutput*videoDataOutPut;
@property(nonatomic,strong)BDCloudAVCaptureSession *capSession;
//@property(nonatomic,strong)avcapture
    //@property(nonatomic,strong)BDCloudAVReplayKitLiveSession *recordSession;
    #define margin_left 10
    #define time_Lab_width 20
    #define time_Lab_height 25
    #define pageSize 1
    #define activeTimeWidth 14
    @end

    @implementation LiveViewController
    -(NSMutableArray *)select_BtnArr{
    if(!_select_BtnArr){
        _select_BtnArr = [NSMutableArray array];
    }
    return _select_BtnArr;
    }
    -(NSMutableArray*)goodsList{
    if(!_goodsList){
        _goodsList = [NSMutableArray array];
    }
    return _goodsList;
    }

    -(UIView *)activeTimeView{
    if(!_activeTimeView){
        _activeTimeView = [[UIView alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*3+30-5+30, screen_height-85, 0, 20)];
       // _activeTimeView.center = self.view.center;
        _activeTimeView.backgroundColor = BUTTON_COLOR;
        _activeTimeView.layer.cornerRadius = 10;
        _activeTimeView.layer.masksToBounds = 1;
        [_activeTimeView addSubview:self.activeTime1];
        [_activeTimeView addSubview:self.activeTime2];
        [_activeTimeView addSubview:self.activeTime3];
        [_activeTimeView addSubview:self.activeTime4];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5+activeTimeWidth*2+3,  (20-activeTimeWidth)/2, 3, activeTimeWidth)];
        label.text = @":";
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
          [_activeTimeView addSubview:label];
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(5+activeTimeWidth*4+3*4-5,  (20-activeTimeWidth)/2, 70, activeTimeWidth)];
        label1.text = @"后互动结束";
        label1.textColor = [UIColor whiteColor];
        label1.textAlignment = NSTextAlignmentCenter;
        label1.font = [UIFont systemFontOfSize:11];
        [_activeTimeView addSubview:label1];
        [self.view addSubview:_activeTimeView];
    }
    return _activeTimeView;
    }
    -(UILabel *)activeTime1{
    if(!_activeTime1){
        _activeTime1 = [[UILabel alloc]initWithFrame:CGRectMake(5, (20-activeTimeWidth)/2, activeTimeWidth, activeTimeWidth)];
        _activeTime1.layer.cornerRadius = activeTimeWidth/2;
        _activeTime1.layer.masksToBounds = 1;
        _activeTime1.textColor = [UIColor whiteColor];
        _activeTime1.backgroundColor = [UIColor redColor];
        _activeTime1.font = [UIFont systemFontOfSize:12];
        _activeTime1.textAlignment = 1;
        _activeTime1.text = @"0";
    }
    return _activeTime1;
    }
    -(UILabel *)activeTime2{
    if(!_activeTime2){
        _activeTime2 = [[UILabel alloc]initWithFrame:CGRectMake(5+activeTimeWidth+3,  (20-activeTimeWidth)/2, activeTimeWidth, activeTimeWidth)];
        _activeTime2.layer.cornerRadius = activeTimeWidth/2;
        _activeTime2.layer.masksToBounds = 1;
        _activeTime2.textColor = [UIColor whiteColor];
        _activeTime2.backgroundColor = [UIColor redColor];
        _activeTime2.font = [UIFont systemFontOfSize:12];
        _activeTime2.textAlignment = 1;
        _activeTime2.text = @"0";
    }
    return _activeTime2;
    }
    -(UILabel *)activeTime3{
    if(!_activeTime3){
        _activeTime3 = [[UILabel alloc]initWithFrame:CGRectMake(5+activeTimeWidth*2+3*2, (20-activeTimeWidth)/2, activeTimeWidth, activeTimeWidth)];
        _activeTime3.layer.cornerRadius = activeTimeWidth/2;
        _activeTime3.layer.masksToBounds = 1;
        _activeTime3.textColor = [UIColor whiteColor];
        _activeTime3.backgroundColor = [UIColor redColor];
        _activeTime3.font = [UIFont systemFontOfSize:12];
        _activeTime3.textAlignment = 1;
        _activeTime3.text = @"0";
    }
    return _activeTime3;
    }
    -(UILabel *)activeTime4{
    if(!_activeTime4){
        _activeTime4 = [[UILabel alloc]initWithFrame:CGRectMake(5+activeTimeWidth*3+3*3, (20-activeTimeWidth)/2, activeTimeWidth, activeTimeWidth)];
        _activeTime4.layer.cornerRadius = activeTimeWidth/2;
        _activeTime4.layer.masksToBounds = 1;
        _activeTime4.textColor = [UIColor whiteColor];
        _activeTime4.backgroundColor = [UIColor redColor];
        _activeTime4.font = [UIFont systemFontOfSize:12];
        _activeTime4.text = @"0";
        _activeTime4.textAlignment = 1;
    }
    return _activeTime4;
    }
    -(void)bilateralFilter:(UISlider *)slide{
    NSInteger index = slide.tag;
    if(index==0){
        [self.session setBeautyBright:slide.value];
    }else if(index==1){
        [self.session setBeautyLevel:slide.value];
    }else if(index==2){
        [self.session setBeautyTone:slide.value];
    }else if(index==3){
        [self.session setColorBright:slide.value];
    }else if(index==4){
        [self.session setColorContrast:slide.value];
    }else{
         [self.session setColorSharpen:slide.value];
    }
    }
    -(UIView *)filter_View{
    if(!_filter_View){
        _filter_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-350, screen_width, 350)];
        _filter_View.backgroundColor =RGBA(0, 0, 0, .8);
        CGFloat itemwith = screen_width/4;
        NSArray *title = @[@"美白",@"磨皮",@"粉嫩",@"亮度",@"对比度",@"锐度"];
        UIColor *whites=[UIColor whiteColor];
            //磨皮
        for(int i =0;i<title.count;i++){
            UILabel *bilateralL = [[UILabel alloc] initWithFrame:CGRectMake(10, 50*i, 40, 45)];
            bilateralL.text = title[i];
            bilateralL.textColor = whites;
            bilateralL.font = [UIFont systemFontOfSize:12];
            [_filter_View addSubview:bilateralL];
        UISlider *bilateralSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 50*i, 250,45)
                                       ];
            bilateralSld.minimumValue = 0;
            bilateralSld.maximumValue = 1;
            if(i==3){
                bilateralSld.minimumValue = -1;
                bilateralSld.maximumValue = 1;
            }
            if(i==4){
                bilateralSld.minimumValue = 0;
                bilateralSld.maximumValue = 4;
            }
            if(i==5){
                bilateralSld.minimumValue = -4;
                bilateralSld.maximumValue = 4;
            }
            bilateralSld.tag = i;
           [bilateralSld addTarget:self action:@selector(bilateralFilter:) forControlEvents:UIControlEventValueChanged];
            [_filter_View addSubview:bilateralSld];
        }
        }
    NSArray *titles = @[@"标清",@"高清",@"超清"];//200,300,400
    for(int i =0;i<3;i++){
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.frame = CGRectMake(70*i+20, 310, 60, 40);
        btn.tag = i;
        [_filter_View addSubview:btn];
        [btn addTarget:self action:@selector(setQuaty:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _filter_View;
    }
    -(UIView *)endpopView{
    if(!_endpopView){
        _endpopView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
        _endpopView.backgroundColor = RGBA(0, 0, 0, 0.7);
        UILabel *labe = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screen_width, 100)];
        labe.center = self.view.center;
        labe.textColor = BUTTON_COLOR;
        labe.textAlignment = NSTextAlignmentCenter;
        labe.font = [UIFont systemFontOfSize:30];
        labe.text = @"直播已结束";
        CGPoint centerPoint = self.view.center;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 150, 40);
        btn.backgroundColor = BUTTON_COLOR;
        [btn setTitle:@"退出直播间" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 20;
        btn.center = CGPointMake(centerPoint.x, centerPoint.y+50);
        [btn addTarget:self action:@selector(timeOut) forControlEvents:UIControlEventTouchUpInside];
        [_endpopView addSubview:btn];
        [_endpopView addSubview:labe];
        [self.view addSubview:_endpopView];
        _endpopView.hidden = 1;
     
    }
    return _endpopView;
    }
    #pragma mark 设置视频上传质量
    -(void)setQuaty:(UIButton *)sender{
    self.filter_View.hidden = 1;
    NSInteger quaty = 0;
     BDCloudAVVideoOutputSettings *VideoSetings = [[BDCloudAVVideoOutputSettings alloc]init];
    NSInteger index = sender.tag;
    switch (index) {
        case 0:
           // quaty = 2000000;
             [VideoSetings setBitRate:2000000];
            break;
            case 1:
           // quaty = 3000000;
             [VideoSetings setBitRate:3000000];
            break;
            case 2:
           // quaty = 4000000;
             [VideoSetings setBitRate:4000000];
            break;
        default:
            break;
    }


    BDCloudAVMovieParameter *param = [[BDCloudAVMovieParameter alloc]init];
    param.videoSettings = VideoSetings;
    NSLog(@",,,,,---%u",(unsigned int)param.videoSettings.bitRate);
    [self.session updateOutputParameter:param];
    }
    -(NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
        NSArray *arr1 = @[@"1分钟后",@"3分钟后",@"5分钟后",@"10分钟后"];
        NSArray *arr2 = @[@"30秒",@"45秒",@"1分钟",@"3分钟",@"20分钟"];
        self.active_TIme = @"30";
        NSArray *arr3 = @[@"全部",@"数码",@"服装",@"只能设备",@"手机"];
        NSArray *arr4 = @[@"全部",@"数码",@"服装",@"只能设备",@"手机",@"衣服配饰"];
        NSArray *arr5 = @[@"全部",@"数码",@"服装"];
        NSDictionary *dic1 = @{@"title":@"设置互动开始时间",@"sid":@"1",@"data":arr1};
        NSDictionary *dic2 = @{@"title":@"设置互动时间",@"sid":@"1",@"data":arr2};
        //  [self.dataSource addObject:dic1];
        [_dataSource addObject:dic2];
    }
    return _dataSource;
    }
    -(UIScrollView *)active_ScroView{
    if(!_active_ScroView){
        _active_ScroView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, screen_width, screen_height-200)];
        _active_ScroView.backgroundColor = RGBA(0, 0, 0, .8);
    }
    return _active_ScroView;
    }
    -(UIView *)active_View{
    if(!_active_View){
        _active_View = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
        _active_View.backgroundColor = RGBA(0, 0, 0, .3);
        _active_View.hidden = 1;
        [self.view addSubview:_active_View];
        [self.view bringSubviewToFront:_active_View];
    }
    return _active_View;
    }
    -(NSMutableArray*)newsComent{
    if(!_newsComent){
        _newsComent = [NSMutableArray array];
    }
    return _newsComent;
    }
    #pragma mark 布局互动界面
    -(void)initActiveView{
    [self.view bringSubviewToFront:self.active_View];
    // UIScrollView *scroView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, screen_width, screen_height-200)];
    [self.active_View addSubview:self.active_ScroView];
    for(UIView *views in [self.active_ScroView subviews]){
        [views removeFromSuperview];
    }
    [self.select_BtnArr removeAllObjects];
    CGFloat tagview_H = 20;
    CGFloat tagview_W = self.active_ScroView.frame.size.width;
    for(int i =0;i<self.dataSource.count;i++){
        NSDictionary *dic = self.dataSource[i];
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, tagview_H, screen_width, 40)];
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 200, 40)];
        title.text = dic[@"title"];
        title.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
        [titleView addSubview:title];
        title.textColor = [UIColor whiteColor];
        [self.active_ScroView addSubview:titleView];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(screen_width-60, 0, 40, 40);
        [btn setImage:[UIImage imageNamed:@"downs"] forState:UIControlStateNormal];
        [titleView addSubview:btn];
        
        tagview_H+=40;
        ActiveTag *tagviews =[[ActiveTag alloc]initWithFrame:CGRectMake(0, tagview_H+0, tagview_W, 0)];
        
        [tagviews setArr:dic[@"data"]];
        tagviews.tag = i;
        tagviews.delegate = self;
        [self.active_ScroView addSubview:tagviews];
        tagview_H+=tagviews.frame.size.height;
    }
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(20, tagview_H, 200, 40)];
    title.text = @"选择商品";
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    [self.active_ScroView addSubview:title];
    title.textColor = [UIColor whiteColor];
    //    NSArray *goods = self.live_Detail[@"goods_list"];
     NSArray *goods = self.goodsList;
    tagview_H+=50;
    for(int i =0;i<goods.count;i++){
        NSDictionary *goodInfo = goods[i];
        UIView *goodsView = [[UIView alloc]initWithFrame:CGRectMake(0, tagview_H, screen_width, 100)];
        UIButton *slect = [UIButton buttonWithType:UIButtonTypeCustom];
        slect.frame = CGRectMake(0, 0, 50, 100);
        [slect setImage:[UIImage imageNamed:@"Oval 6"] forState:UIControlStateNormal];
          [slect setImage:[UIImage imageNamed:@"Group 7"] forState:UIControlStateSelected];
        [slect addTarget:self action:@selector(selctgoods:) forControlEvents:UIControlEventTouchUpInside];
        slect.tag = 500+i;
        [self.select_BtnArr addObject:slect];
        if(i==0){
            slect.selected = 1;
            self.goodId = goodInfo[@"goods_id"];
            
        }

       // goodsView.backgroundColor = [UIColor redColor];
        UIImageView *imags = [[UIImageView alloc]initWithFrame:CGRectMake(60, 10, 80, 80)];
        NSURL *url = [NSURL URLWithString:goods[i][@"thumb"]];
        imags.layer.cornerRadius  = 5;
        imags.layer.masksToBounds = 1;
        [imags sd_setImageWithURL:url];
        UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(150, 10, screen_width-160, 30)];
        name.text = goodInfo[@"title"];
        name.font = [UIFont systemFontOfSize:15];
        name.textColor = [UIColor whiteColor];
        UILabel *desc = [[UILabel alloc]initWithFrame:CGRectMake(150, 40, screen_width-160, 30)];
        desc.text = [goodInfo[@"content"]isEqualToString:@""]?@"暂无":goodInfo[@"content"];
        desc.font = [UIFont systemFontOfSize:13];
        desc.textColor = [UIColor whiteColor];
        UILabel *price = [[UILabel alloc]initWithFrame:CGRectMake(150, 70, screen_width-160, 30)];
        price.text = [NSString stringWithFormat:@"¥%@", goodInfo[@"buy_price"]];
        price.font = [UIFont systemFontOfSize:18];
        price.textColor =PRICE_COLOR;
        [goodsView addSubview:imags];
        [goodsView addSubview:name];
        [goodsView addSubview:desc];
        [goodsView addSubview:price];
        [goodsView addSubview:slect];
        [self.active_ScroView addSubview:goodsView];
        tagview_H+=100;
    }
    Regular_Btn *confirm = [Regular_Btn buttonWithType:UIButtonTypeCustom];
    confirm.frame = CGRectMake(20, tagview_H+20, screen_width-40, 50);
    confirm.backgroundColor = BUTTON_COLOR;
    [confirm setTitle:@"开启" forState:UIControlStateNormal];
    [confirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(startActive) forControlEvents:UIControlEventTouchUpInside];
    [self.active_ScroView addSubview:confirm];
    self.active_ScroView.contentSize = CGSizeMake(0, tagview_H+200);
    CGFloat orgY = screen_height-tagview_H-100;
    if(orgY<0){
        orgY = 0;
    }
    self.active_ScroView.frame = CGRectMake(0, orgY, screen_width, screen_height);
    }
    -(void)handleSelectATag:(NSString *)keyWord andTag:(NSInteger)index AndPindex:(NSInteger)pindex{
    //NSArray *arr2 = @[@"1分钟",@"3分钟",@"5分钟",@"10分钟"];
    //NSArray *arr2 = @[@"30秒",@"45秒",@"1分钟",@"3分钟"];
    if(index==0){
        //1分钟
        self.active_TIme = @"30";
    }else if (index==1){
        //
        self.active_TIme = @"45";
    }else if (index==2){
        self.active_TIme = @"60";
    }
    else if(index==3){
        self.active_TIme = @"180";
    }else{
        self.active_TIme = @"1200";
    }
    }
    #pragma mark 连接socket
    -(void)connectHost{
    //    _socket.delegate = nil;
    //
    //    [_socket close];
    NSDictionary *dic = [XTool GetDefaultInfo:HOST_USER];
    NSString *str = [NSString stringWithFormat:@"scene=room&room_no=%@&token=%@&username=%@&u_type=2",self.roomNum,dic[@"token"],dic[@"nickname"]];
    NSString *strs = [NSString stringWithFormat:@"%@:%@?%@",SOCKET_HOST,SOCKET_PORT,str];
    NSString *encodedValue = [strs stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.socket = [[JFRWebSocket alloc] initWithURL:[NSURL URLWithString:encodedValue] protocols:@[@"chat",@"superchat"]];
    self.socket.delegate = self;
    [self.socket connect];
    //    [[C_SocketUtility instance] SRWebSocketOpenWithURLString:encodedValue];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidOpen) name:kWebSocketDidOpenNote object:nil];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];

    //    NSLog(@"str ==%@",str);
    //    NSString *strs = [NSString stringWithFormat:@"%@:%@?%@",SOCKET_HOST,SOCKET_PORT,str];
    //    NSString *encodedValue = [strs stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:encodedValue]];
    //    _socket = [[SRWebSocket alloc] initWithURLRequest:request];
    //    _socket.delegate = self;
    //    [_socket open];
    }
    -(void)websocketDidConnect:(JFRWebSocket*)socket {
    NSLog(@"websocket is connected");
    NSLog(@"开启成功");
    }
    -(void)websocketDidDisconnect:(JFRWebSocket*)socket error:(NSError*)error {
    NSLog(@"websocket is disconnected: %@",[error localizedDescription]);
    [WToast showWithText:@"断开连接"];
    }
    -(void)websocket:(JFRWebSocket*)socket didReceiveMessage:(NSString*)string {
    //NSLog(@"got some text: %@",string);
    NSDictionary *dic =   [self StrtoJson:string];
    NSInteger types = [dic[@"code"]integerValue];
    if(types==1||types==2||types==98){
        //消息和弹幕
        if(types==1||types==98){
            //系统消息
            Danmu_Model *model = [[Danmu_Model alloc]init];
            
            model.content = dic[@"data"][@"mes"];
            model.type = 0;
            [self.newsComent insertObject:model atIndex:0];
        }else if (types==2){
            Danmu_Model *model = [[Danmu_Model alloc]init];
            //  model.content =[NSString stringWithFormat:@"%@   %@",dic[@"data"][@"user_name"], dic[@"data"][@"mes"]];
            model.content =dic[@"data"][@"mes"];
            model.type = 1;
            model.userName = dic[@"data"][@"user_name"];
            NSInteger level = [dic[@"data"][@"groupid"]integerValue];
            NSString *imagestr = [NSString stringWithFormat:@"level%ld",level-1];
            NSTextAttachment* attach = [[NSTextAttachment alloc] init];
            
            NSURL *urls = [NSURL URLWithString:dic[@"data"][@"group_logo"]];
            
            [attach setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:urls]]];
            NSAttributedString* attStr1 = [NSAttributedString attributedStringWithAttachment:attach];
            NSMutableAttributedString* attStr2 =[ [NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@" %@:",dic[@"data"][@"user_name"]]];
            UIColor *usernameColor = [XTool colorWithHexString:dic[@"data"][@"group_color"]];
      
            NSDictionary * secondAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:usernameColor,};
            [attStr2 setAttributes:secondAttributes range:NSMakeRange(0, attStr2.length)];
            NSMutableAttributedString* attStr = [[NSMutableAttributedString alloc] initWithAttributedString:attStr1];
            [attStr appendAttributedString:attStr2];
            [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@",model.content]]];
            attach.bounds = CGRectMake(0, -4, 30, 15);
            model.contentAttr = attStr;
            [self.newsComent insertObject:model atIndex:0];
        }else if (types==98){
            //用户离开直播间
        //    [self.newsComent insertObject:dic[@"data"][@"mes"] atIndex:0];
        }
        if(self.left_tab){
            [self.left_tab reloadData];
        }
    }else{
        //互动
        if(types==4){
            //互动开始
        }else if (types==5){
            //互动结束
            [self loadresult];
        }else if (types==6){
            UILabel *like_Num = (UILabel *)[self.view viewWithTag:1025];
            //            like_Num.text =[NSString stringWithFormat:@"%@",response[@"data"][@"praise"]];
            CGFloat praise =  [dic[@"data"][@"zan"]floatValue];
            if(praise>10000.00){
                CGFloat num  =  [dic[@"data"][@"zan"]floatValue]/10000;
                like_Num.text =[NSString stringWithFormat:@"%.2fw",num];
            }else{
                like_Num.text =[NSString stringWithFormat:@"%@", dic[@"data"][@"zan"]];
            }
            
            UILabel *guest = (UILabel *)[self.view viewWithTag:1026];
            guest.text = [NSString stringWithFormat:@"%@", dic[@"data"][@"online_number"]];
        }
    }
    }
    - (void)SRWebSocketDidOpen {
    NSLog(@"开启成功");
    //在成功后需要做的操作。。。

    }

    - (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    //收到服务端发送过来的消息
    id message = note.object;
    NSDictionary *dic =   [self StrtoJson:message];
    NSInteger types = [dic[@"code"]integerValue];
    if(types==1||types==2||types==98){
        //消息和弹幕
        if(types==1){
            //系统消息
            [self.newsComent insertObject:dic[@"data"][@"mes"] atIndex:0];
        }else if (types==2){
            NSString *mess = [NSString stringWithFormat:@"%@：%@",dic[@"data"][@"user_name"],dic[@"data"][@"mes"]];
            [self.newsComent insertObject:mess atIndex:0];
        }else if (types==98){
            //用户离开直播间
            [self.newsComent insertObject:dic[@"data"][@"mes"] atIndex:0];
        }
        if(self.left_tab){
            [self.left_tab reloadData];
            
        }
    }else{
        //互动
        if(types==4){
            //互动开始
        }else if (types==5){
            //互动结束
            [self loadresult];
        }
    }
    }
    #pragma mark socket代理
    //接受消息
    - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
    {

    NSDictionary *dic =   [self StrtoJson:message];
    NSInteger types = [dic[@"code"]integerValue];
    if(types==1||types==2||types==98){
        //消息和弹幕
        if(types==1){
            //系统消息
            [self.newsComent insertObject:dic[@"data"][@"mes"] atIndex:0];
        }else if (types==2){
            NSString *mess = [NSString stringWithFormat:@"%@：%@",dic[@"data"][@"user_name"],dic[@"data"][@"mes"]];
            [self.newsComent insertObject:mess atIndex:0];
        }else if (types==98){
            //用户离开直播间
            [self.newsComent insertObject:dic[@"data"][@"mes"] atIndex:0];
        }
        if(self.left_tab){
            [self.left_tab reloadData];

        }
    }else{
        //互动
        if(types==4){
            //互动开始
        }else if (types==5){
            //互动结束
            [self loadresult];
        }
    }
    }
    - (void)webSocketDidOpen:(SRWebSocket *)webSocket
    {
    NSLog(@"socket success==%@",webSocket);
    }
    - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
    {
    [WToast showWithText:@"已断开连接，重新连接中"];
    _socket = nil;
    [self connectHost];
    NSLog(@"socket fail==%@",error);
    }
    - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
    {
    _socket = nil;
    }
    -(void)changeStr:(NSString*)str{
    }
    - (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload
    {

    }

    -(NSDictionary *)StrtoJson:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    return dic;
    }
    -(NSString *)dictiontoJson:(NSDictionary *)diction{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:diction
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
    }
    -(NSString *)dictiontoJson:(NSDictionary *)diction andCode:(NSInteger)code{
    NSMutableString *str = [NSMutableString string];
    [str appendString:@"{"];

    [str appendString:@"\"code\":"];
    [str appendFormat:@"%ld,",(long)code];
    //    [str appendString:@"{"];

    [str appendString:@"\"data\":"];
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:diction
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    [str appendString:jsonString];
    [str appendString:@"}"];
    return str;
    }
    #pragma mark 开启互动
    -(void)startActive{
    self.active_View.hidden = 1;

    //    NSDictionary *param = @{@"id":self.live_id,@"countdown_time":self.active_TIme,@"current_goodsid":self.goodId,@"u_type":@"2",@"room_no":self.roomNum};
    //    NSString *str = [self dictiontoJson:param andCode:4];
    //    [_socket send:str];

    self.active_View.hidden = 1;
    NSDictionary *params = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"openact",@"id":self.live_id,@"countdown_time":self.active_TIme,@"current_goodsid":self.goodId};
    [self weqPostHandle:params success:^(id response) {
        if(response){
          //  [WToast showWithText:@"开启成功"];
            [self.goodsList removeObjectAtIndex:self.selectGoodIdx];
            self.openActive = 1;
            self.activeTime = [self.active_TIme integerValue];
           // [self performSelector:@selector(sendAcitive) withObject:nil afterDelay:3];
            [self performSelectorOnMainThread:@selector(sendAcitive) withObject:nil waitUntilDone:0];
        }
    } failure:^(NSError *error) {
        
    }];
    }
    -(void)sendAcitive{

    NSDictionary *param = @{@"id":self.live_id,@"countdown_time":self.active_TIme,@"current_goodsid":self.goodId,@"u_type":@"2",@"room_no":self.roomNum};
    NSString *str = [self dictiontoJson:param andCode:4];
    [self.socket writeString:str];
[self performSelector:@selector(showActiveTimes) withObject:nil afterDelay:4];

    }
    -(void)sendAcitive:(NSInteger)type{
    NSDictionary *param = @{@"id":self.live_id,@"countdown_time":self.active_TIme,@"current_goodsid":self.goodId,@"u_type":@"2",@"room_no":self.roomNum};
    NSString *str = [self dictiontoJson:param andCode:5];
     [self.socket writeString:str];
    }
    #pragma mark 选择商品
    -(void)selctgoods:(UIButton *)sender{
    sender.selected = !sender.selected;
    NSInteger index = sender.tag-500;
    self.selectGoodIdx = index;
    for(UIButton *btn in self.select_BtnArr){
        if(btn!=sender){

            btn.selected = 0;
        }
    }
    NSArray *goods = self.goodsList;
    self.goodId = goods[index][@"goods_id"];
    }
    #pragma mark 懒加载
    -(UITableView *)left_tab{
    if(!_left_tab){
        _left_tab = [[UITableView alloc]initWithFrame:CGRectMake(0, screen_height-340, screen_width, 170) style:UITableViewStylePlain];
        _left_tab.delegate = self;
        _left_tab.dataSource = self;
        _left_tab.backgroundColor = [UIColor clearColor];
        _left_tab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _left_tab.transform = CGAffineTransformMakeScale(1, -1);//翻转180
        //_left_tab.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_left_tab];
    }
    return _left_tab;
    }
    -(UIView *)hostInfoView{
    if(!_hostInfoView){
        NSInteger margin_Top = KISIphoneX?55:30;
        //顶部主播简介
        _hostInfoView = [[UIView alloc] init];
        _hostInfoView.frame = CGRectMake(17.5, margin_Top,176,40);
        _hostInfoView.layer.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6].CGColor;
        _hostInfoView.layer.cornerRadius = 20;
    }
    return _hostInfoView;
    }
    #pragma mark 互动倒计时的视图
    //-(UIView *)activeTimeView{
    //    if(!_activeTimeView){
    //
    //            NSInteger margin_Top = KISIphoneX?55:30;
    //            //顶部主播简介
    //            _activeTimeView = [[UIView alloc] init];
    //            _activeTimeView.frame = CGRectMake(17.5, margin_Top,176,40);
    //            _activeTimeView.layer.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6].CGColor;
    //            _activeTimeView.layer.cornerRadius = 20;
    //}
    //     return _activeTimeView;
    //}
    #pragma mark 左边滚动视图代理
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.newsComent.count;
    }
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cell";
    DanmuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell =[[[NSBundle mainBundle]loadNibNamed:@"DanmuCell" owner:self options:nil]lastObject];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    Danmu_Model *model  = self.newsComent[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSString *danmu = model.content;
    CGFloat widthss = 0;
    if(model.type==0){
        widthss= [XTool calculateRowWidth:danmu andHeight:26 andSize:13];
    }else{
        danmu = [NSString stringWithFormat:@"%@  %@",model.userName,model.content];
        widthss = [XTool calculateRowWidth:danmu andHeight:26 andSize:13]+35;
    }
    CGRect orginRc = cell.danmView.frame;
    cell.danmView.frame = CGRectMake(orginRc.origin.x,orginRc.origin.y, widthss+30, 26);

    CGRect LabOrg = cell.DanmuText.frame;
    cell.DanmuText.frame = CGRectMake(10, 0, widthss+20+20, 26);
    cell.contentView.transform=CGAffineTransformMakeScale(1, -1);
    if(model.type==0)
        cell.DanmuText.text = danmu;
    else cell.DanmuText.attributedText = model.contentAttr;

    return cell;

    }
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 29;
    }
    #pragma mark 开启或者关闭弹幕
    -(void)opendDm{
    self.openDm = !self.openDm;
    self.left_tab.hidden = !self.openDm;
    }
    #pragma mark 获取弹幕数据
    -(void)loadDam{
    //    NSDictionary *param = @{@"ctrl":@"common",@"ac":@"live",@"ta":@"get_danmu",@"act_id":self.live_id,@"page":[NSString stringWithFormat:@"%ld",(long)self.Dampage],@"psize":[NSString stringWithFormat:@"%d",pageSize]};
    //    NSLog(@"页数===%ld",(long)self.Dampage);
    //    [self loadDm:param success:^(id response) {
    //        if(response){
    //            self.Dampage++;
    //            NSArray *datas = response[@"data"];
    //            for(int i =0;i<datas.count;i++){
    //                [self.newsComent insertObject:datas[i][@"content"] atIndex:0];
    //                NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    //                [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];
    //            }
    //
    //        }
    //
    //    } failure:^(NSError *error) {
    //
    //    }];
    }
    -(void)loadnewsComents{
    for(int i =0;i<10;i++){
        NSString *str = [NSString stringWithFormat:@"欢迎%d进入直播间",i];
        //  [self.newsComent addObject:str];
    }
    //    [self.newsComent insertObject:@"欢迎 板扎科技 进入直播间" atIndex:0];
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    //  [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];


    }
    //暂停定时器(只是暂停,并没有销毁timer)
    -(void)pauseTimer{
    [self.rand_Timer setFireDate:[NSDate distantFuture]];
    }
    //继续计时
    -(void)continueTimer{
    [self.rand_Timer setFireDate:[NSDate distantPast]];
    }

    //开始随机
    -(void)startimer{
    //  self.random_Btn.hidden = 0;
    [self.rand_Timer fire];
    }
    //暂停并销毁
    -(void)stopTimer{
    [self.rand_Timer invalidate];
    self.rand_Timer = nil;
    }
    -(NSTimer*)rand_Timer{
    if (!_rand_Timer) {
        _rand_Timer =[NSTimer scheduledTimerWithTimeInterval:0.2  target:self  selector:@selector(randoms) userInfo:nil  repeats:YES];
    }
    return _rand_Timer;
    }
    //开启、关闭录屏
    -(void)record{
    //    self.isrepeate = !self.isrepeate;
    //    if(self.isrepeate==1){
    //        [self.repeateSession start];
    //    }else{
    //        [self.repeateSession stop];
    //    }
    }
    #pragma mark 开播前的提示确认操作
    -(void)showDiagAlert{

    self.diagAlertView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
    self.diagAlertView.backgroundColor = RGBA(0, 0, 0, .5);
    UIButton *confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    confirm.frame = CGRectMake(20, screen_height/2-55, screen_width-40, 50);
    confirm.layer.cornerRadius = 5;
    confirm.layer.masksToBounds = 1;
    confirm.backgroundColor = BUTTON_COLOR;
    [confirm setTitle:@"准备好了，开始直播" forState:UIControlStateNormal];
    [self.diagAlertView addSubview:confirm];


    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    cancel.frame = CGRectMake(20, screen_height/2+5, screen_width-40, 50);
    cancel.layer.cornerRadius = 5;
    cancel.layer.masksToBounds = 1;
    cancel.backgroundColor = BUTTON_COLOR;
    [cancel setTitle:@"暂不开始" forState:UIControlStateNormal];
    [self.diagAlertView addSubview:cancel];

    [confirm addTarget:self action:@selector(confirmLive) forControlEvents:UIControlEventTouchUpInside];
    [cancel addTarget:self action:@selector(exit_live) forControlEvents:UIControlEventTouchUpInside];

    [[UIApplication sharedApplication].keyWindow addSubview:self.diagAlertView];
    }
    #pragma mark 确认开播
    -(void)confirmLive{
    [self.diagAlertView removeFromSuperview];
        
      //  [self checkMike];
   [self loadliveInfo];

    }
    #pragma mark 退出直播间
    -(void)exit_live{
     [self.diagAlertView removeFromSuperview];
    //    [self.session stopPreview];
    //    [self.navigationController popViewControllerAnimated:0];
    }
    #pragma mark 主播打开底部主播功能
    #pragma mark 功能列表弹出框
    -(void)openmorefunc{
    hostPopFunc *pop = [[hostPopFunc alloc]init];
    pop.delegate = self;
    [pop show:self.danmustatus andCollect:self.iscollect];
    }
    -(void)AlertView:(pop_func *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex Andtitle:(nonnull NSString *)change{
    if(buttonIndex==0){
        //分享
    }else if (buttonIndex==1){
        //开启互动
        self.active_View.hidden = 0;
       [self initActiveView];
    }else if (buttonIndex==2){
        //关闭弹幕
        UILabel *titles =(UILabel *) [alertView viewWithTag:1024+2];
        self.danmustatus = !self.danmustatus;
        [self opendDm];
        
    }else if(buttonIndex==3){
        //关闭直播
        [self close_Live];
    }
    }
    #pragma mark 选择美颜效果
    -(void)selectFilter:(UIButton *)sender{
    //    self.filter_View.hidden = 1;
    CGFloat br = 0.0f;
    CGFloat be= 0.0f;
    CGFloat to = 0.0f;
    if(sender.tag==0){
        br = 0.65;
        be = 0.80;
        to = 0.65;
    }else if (sender.tag==1){
        br = 0.6;
        be = 0.35;
        to = 0.95;
    }else if (sender.tag==2){
        br = 0.65;
        be = 0.35;
        to = 0.45;
    }else{
        br = 0.4;
        be = 0.55;
        to = 0.05;
    }
    [self.session setBeautyBright:br];//设置美白
    [self.session setBeautyLevel:be];//设置磨皮
    [self.session setBeautyTone:to];//
    //    [self.session setColorBright:br];
    //    [self.session setColorHue:br];
    //    [self.session setColorContrast:to];
    //    [self.session setColorSharpen:be];

    // self.beautyFilter = [[BDCloudAVNaturalBeautyFilter alloc]init];
    //  self.beautyFilter.brightLevel =br;
    // self.beautyFilter.beautyLevel = be;
    //  self.beautyFilter.toneLevel = to;
    //  [self.session addFilter:self.beautyFilter];
    }
    #pragma mark 买商品的弹出框
    -(void)showgoods{
    self.filter_View.hidden = 0;
    //    hostPopFunc *view = [[hostPopFunc alloc]init];
    //    [view show];
    }
    -(void)viewWillAppear:(BOOL)animated{
    //进入直播间先判断用户是否完善了信息

    }
    //视频效果调整
    -(void)initFilter{
    self.bottomControlView = [[UIView alloc] initWithFrame:CGRectMake(0, screen_height-200, 320, 118)];
    //   [self.view addSubview:self.bottomControlView];


    //    //磨皮
    //    UILabel *bilateralL = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 25)];
    //    bilateralL.text = @"磨皮";
    //    bilateralL.font = [UIFont systemFontOfSize:12];
    //    [self.bottomControlView addSubview:bilateralL];
    //
    //    UISlider *bilateralSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 10, 250, 30)
    //                               ];
    //    bilateralSld.minimumValue = 0;
    //    bilateralSld.maximumValue = 1;
    //    //    bilateralSld.value = 0;
    //    [bilateralSld addTarget:self action:@selector(bilateralFilter:) forControlEvents:UIControlEventValueChanged];
    //    [self.bottomControlView addSubview:bilateralSld];
    //
    //
    //    //美白
    //    UILabel *brightnessL = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 40, 25)];
    //    brightnessL.text = @"美白";
    //    brightnessL.font = [UIFont systemFontOfSize:12];
    //    [self.bottomControlView addSubview:brightnessL];
    //
    //    UISlider *brightnessSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 40, 250, 30)
    //                                ];
    //    brightnessSld.minimumValue = 0;
    //    brightnessSld.maximumValue = 1;
    //    //    brightnessSld.value = 0;
    //    [brightnessSld addTarget:self action:@selector(brightnessFilter:) forControlEvents:UIControlEventValueChanged];
    //    [self.bottomControlView addSubview:brightnessSld];
    }
    #pragma mark 获取中奖结果
    -(void)loadresult{
    NSDictionary *params = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"whoprize",@"id":self.live_id};
    [self weqPostHandle:params success:^(id response) {
        NSLog(@"中奖结果==%@",response);
        if(response){
            Result_popView *alert = [[Result_popView alloc]init];
            alert.delegate = self;
            NSLog(@"传递的参数......%@",response[@"data"]);
            [alert showWithData:response[@"data"] andisHost:1];

            
        }else{
            
        }
    } failure:^(NSError *error) {
        
    }];
    }
    -(void)loadAddress{
    //    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"member",@"op":@"address",@"ta":@"index"};
    //    [self weqPostHandle:params success:^(id response) {
    //        if(response){
    //            if([response[@"data"][@"name"]isEqualToString:@""]||[response[@"data"][@"address"]isEqualToString:@""]){
    //                Regist2ViewController *vc = [[Regist2ViewController alloc]init];
    //                [self pushSecondVC:vc];
    //            }
    //        }else{
    //            Regist2ViewController *vc = [[Regist2ViewController alloc]init];
    //            [self pushSecondVC:vc];
    //        }
    //    } failure:^(NSError *error) {
    //
    //    }];
    }
    -(void)cacuActiveOutTime:(NSInteger )totalTime{

    NSInteger seconds = totalTime;
    NSInteger hour = seconds/3600;
    //    if(hour>0){
    //        self.dayLb.hidden= 0;
    //        self.dayLb.text = [NSString stringWithFormat:@"%ld小时",hour];
    //
    //        UILabel *timedes = (UILabel *)[self.view viewWithTag:1028];
    //        timedes.frame = CGRectMake(timedes.frame.origin.x, screen_height-150, 100, 20);
    //     }
    NSString *str_hour = [NSString stringWithFormat:@"%ld",seconds/3600];
    //format of minute
    NSInteger minute = (seconds%3600)/60;
    NSString *str_minute = [NSString stringWithFormat:@"%ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of minute
    // NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    if(str_minute.length>1){
        self.activeTime1.text = [str_minute substringWithRange:NSMakeRange(0, 1)];
        self.activeTime2.text =  [str_minute substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.activeTime1.text = @"0";
        self.activeTime2.text = str_minute;
    }
    //format of second
    // NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    if(str_second.length>1){
        self.activeTime3.text = [str_second substringWithRange:NSMakeRange(0, 1)];
        self.activeTime4.text =  [str_second substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.activeTime3.text = @"0";
        self.activeTime4.text = str_second;
    }

    }
    -(NSString *)getMMSSFromSS:(NSInteger )totalTime {

    NSInteger seconds = totalTime;
    NSInteger hour = seconds/3600;
    if(hour>0){
        self.dayLb.hidden= 0;
        self.dayLb.text = [NSString stringWithFormat:@"%ld小时",hour];
        
        UILabel *timedes = (UILabel *)[self.view viewWithTag:1028];
        timedes.frame = CGRectMake(timedes.frame.origin.x, screen_height-150, 100, 20);
        // self.dayLb = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    }
    NSString *str_hour = [NSString stringWithFormat:@"%ld",seconds/3600];
    //format of minute
    NSInteger minute = (seconds%3600)/60;
    NSString *str_minute = [NSString stringWithFormat:@"%ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of minute
    // NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    if(str_minute.length>1){
        self.time_lab1.text = [str_minute substringWithRange:NSMakeRange(0, 1)];
        self.time_lab2.text =  [str_minute substringWithRange:NSMakeRange(1, 1)];
    }else{
         self.time_lab1.text = @"0";
        self.time_lab2.text = str_minute;
    }
    //format of second
    // NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    if(str_second.length>1){
        self.time_lab3.text = [str_second substringWithRange:NSMakeRange(0, 1)];
        self.time_lab4.text =  [str_second substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab3.text = @"0";
        self.time_lab4.text = str_second;
    }
    NSString *format_time = [NSString stringWithFormat:@"%@分钟%@秒",str_minute,str_second];


    return format_time;
    }
    //直播结束
    -(void)endlive{
    [self.session stopPreview];
    [self.session stop];
    NSDictionary *param = @{@"ctrl":@"live_merch",@"ac":@"store",@"op":@"activity",@"ta":@"activityend",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            [WToast showWithText:@"直播已结束"];
            [self performSelector:@selector(close_Live) withObject:nil afterDelay:5];
        }
    } failure:^(NSError *error) {
        
    }];
    }
    -(void)back{
    [self.navigationController popViewControllerAnimated:1];
    }
    //抢购倒计时
    -(void)cutdown{

    __block  NSInteger start = 0;


    // start = self.end_time;
    if(self.isstart==1){
        start = self.end_time;
    }else{
        start = self.startlive_time;
    }
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
        self.coutHart++;
        if(self.coutHart%10==0){
            NSDictionary *param = @{@"id":self.live_id,@"countdown_time":self.active_TIme,@"current_goodsid":self.goodId,@"u_type":@"2",@"room_no":self.roomNum};
            NSString *str = [self dictiontoJson:param andCode:99];
            [self.socket writeString:str];
           // [self->_socket send:str];
        }
        if(self.openActive==1){
            //互动倒计时
          if(self.activeTime>0){
              if(self.isrobing==1){
               self.activeTime--;
                   [self cacuActiveOutTime:self.activeTime];
              }
             }else{
              //  self.isrobing=0;
                self.isrobing = 0;
                self.openActive = 0;
                [self sendAcitive:5];
                [self showActiveTime:0];
              //  [self loadresult];
            }
        }
        NSLog(@"GCD-----%@",[NSThread currentThread]);
        [self loadDam];
         [self loadLikeNum];
        if(self.end_time>0){
            self.end_time--;
            [self getMMSSFromSS:self.end_time];
        }else{
            //直播已结束
            self.endpopView.hidden = 0;
            [self.view bringSubviewToFront:self.endpopView];
            [self requestClose];//向服务器请求更新直播状态
            [self sendCloseNoti:96];//socket 发送结束指令
           [self.session stop];
            [self.session stopPreview];
            self.session = nil;
            dispatch_cancel(self.timer);
            self.timer = nil;
        }

    });

    //4.开始执行
    dispatch_resume(timer);
    //
    self.timer = timer;

    }
    //#pragma mark 获取弹幕
    //-(void)loadnewsComents{
    //    for(int i =0;i<10;i++){
    //        NSString *str = [NSString stringWithFormat:@"欢迎%d进入直播间",i];
    //        //  [self.newsComent addObject:str];
    //    }
    //    [self.newsComent insertObject:@"欢迎进入直播间" atIndex:0];
    //    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    //
    //    [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];
    //
    //
    //}
    //获取活动的观看人数和点赞人数
    -(void)loadLikeNum{
    //    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"total",@"id":self.live_id};
    //    [self weqPostHandle:param success:^(id response) {
    //        SLog(@"点赞信息===%@",response);
    //        if(response){
    //
    //            UILabel *like_Num = (UILabel *)[self.view viewWithTag:1025];
    //           // like_Num.text =[NSString stringWithFormat:@"%@",response[@"data"][@"praise"]];
    //            CGFloat praise =  [response[@"data"][@"praise"]floatValue];
    //            if(praise>10000.00){
    //                CGFloat num  = [response[@"data"][@"praise"]floatValue]/10000;
    //                like_Num.text =[NSString stringWithFormat:@"%.2fw",num];
    //            }else{
    //                like_Num.text =[NSString stringWithFormat:@"%@",response[@"data"][@"praise"]];
    //            }
    //
    //
    //            UILabel *guest = (UILabel *)[self.view viewWithTag:1026];
    //            guest.text = [NSString stringWithFormat:@"%@",response[@"data"][@"total_member"]];
    //
    //        }
    //    } failure:^(NSError *error) {
    //
    //    }];
    }
    -(void)startlive{

    }
    #pragma mark 获取活动详情
    -(void)loadliveInfo{
        UIButton *btn = (UIButton *)[self.view viewWithTag:2225];
        [btn removeFromSuperview];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_HUD];
    _HUD.label.text = @"获取直播数据";
    //细节文字
    _HUD.detailsLabel.text = @"请耐心等待";
    NSDictionary *param = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"detail",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        
        if(response){
            self.startlive_time =[response[@"data"][@"start_time"]integerValue]-[response[@"data"][@"now_time"]integerValue];
            self.cutdown_time = [response[@"data"][@"countdown_time"]integerValue]-[response[@"data"][@"now_time"]integerValue];
            self.end_time =  [response[@"data"][@"end_time"]integerValue]-[response[@"data"][@"service_time"]integerValue];
            if(self.end_time<0){
                [WToast showWithText:@"直播已结束"];
                [self.navigationController popToRootViewControllerAnimated:1];
                return ;
            }
             [self connectHost];
            self.is_start = 1;
            [self.HUD removeFromSuperview];
            [ self.goodsList addObjectsFromArray:response[@"data"][@"goods_list"]];
            self.HUD = nil;
            self.live_Detail = response[@"data"];
             self.bdlive_Url = response[@"data"][@"bdlive"];
            UILabel *label =(UILabel *)[self.hostInfoView viewWithTag:152];
            UILabel *endDes = (UILabel *)[self.view viewWithTag:1028];
            endDes.text = @"距直播结束";
            endDes.textColor = [UIColor whiteColor];
            label.text = [NSString stringWithFormat:@"房间号:%@ 粉丝:%@",response[@"data"][@"store"][@"room_number"],response[@"data"][@"anchor_list"][0][@"anchor_fans"]];//h更新主播房间号和粉丝
           UILabel *rule_Lab =(UILabel *)[self.view viewWithTag:1024];
          //  rele_lab.text =[NSString stringWithFormat:@"本场规则：在随机变化的数字中，最先点中%ld",(long)self.rewad_Num];
            NSInteger live_type = [self.live_Detail[@"live_type"]integerValue];
              NSInteger game_type= [response[@"data"][@"game_type"]integerValue];//游戏类型，1位数字轮盘，2位知识竞赛，3为商品营销
            if(live_type==1){
                if(game_type==1){
                    self.rewad_Num = [self.live_Detail[@"game"][@"right_num"]integerValue];
                    rule_Lab.text =[NSString stringWithFormat:@"本场规则：在随机变化的数字中，最先点中%ld",(long)self.rewad_Num];
                }else{
                    rule_Lab.text =@"本场规则：最先答对题目的人可中奖";
                }
            }else{
                rule_Lab.text =@"本场规则：在随机的礼物中最先点到中奖礼物的可中奖";
            }
           
            NSLog(@"z结束时间===%ld",(long)self.end_time);
             [self start_Live];
            if(self.startlive_time>0){

            }
            if(self.end_time>0&&self.startlive_time<0){

            }
          
        }else{
            [WToast showWithText:@"直播时间未到"];
        }
    } failure:^(NSError *error) {
        
    }];
    }
    -(void)start_Live{
    [self.Audionsession setCategory:AVAudioSessionCategoryRecord error:nil];
    
       // http://music.taihe.com/album/194037//
//        NSString *str = [[NSBundle mainBundle]pathForResource:@"wmbyy" ofType:@"mp3"];
//       // NSString *musicStr = @"http://dev.sharepanzer.com/wmbyy.mp3";
//        NSURL *musicPlay = [NSURL URLWithString:str];
//        CMTime start = kCMTimeZero;
//        CMTime duration = CMTimeMakeWithSeconds(200, 1);
//        CMTimeRange range = CMTimeRangeMake(start, duration);
//        [self.session setMusic:str];
//        [self.session setMusicEnable:YES];
//        [self.session setMusicVolume:0.5];
//        [self.session setMixOutputVolume:1];
     //   [self.session setMusicRange:range];
      //  [self.session setReverbDryWetLevel:80];
        [self.session start];
//        AVAsset *asset = [AVAsset assetWithURL:musicPlay];
//
//        //    导出素材
//        AVAssetExportSession *exporter = [[AVAssetExportSession alloc]initWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
//
//        CMTime start = CMTimeMakeWithSeconds(0, asset.duration.timescale);
//        CMTime duration = CMTimeMakeWithSeconds(500 - 0,asset.duration.timescale);
//        [self.session setMusicRange:CMTimeRangeMake(start, duration)];
        

     

       
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    self.danmustatus = 1;
    // [self left_tab];
    [self cutdown];
    NSInteger margin_Top = KISIphoneX?55:30;

    UIButton *btn = (UIButton *)[self.view viewWithTag:1101];
    btn.frame = CGRectMake(screen_width-50, screen_height-150, 40, 40);
    UIButton *btn1 = (UIButton *)[self.view viewWithTag:1102];
    [btn1 removeFromSuperview];
    UILabel *lab = (UILabel *)[self.view viewWithTag:1028];
    //  [lab removeFromSuperview];
    //右边的点赞和分享元素
    UIImageView *share_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-100, 25, 25)];
    share_img.image = [UIImage imageNamed:@"Group 4 Copy 2"];
    share_img.contentMode = UIViewContentModeScaleAspectFit;
    //  [self.player.view addSubview:share_img];


    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    share_Btn.frame = CGRectMake(screen_width-50, screen_height-100, 40, 40);
    [share_Btn setImage:[UIImage imageNamed:@"Group 4 Copy 2"] forState:UIControlStateNormal];
    [share_Btn addTarget:self action:@selector(openmorefunc) forControlEvents:UIControlEventTouchUpInside];
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.view addSubview:share_Btn];


    self.like_image = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-160, 30, 30)];
    self.like_image.contentMode = UIViewContentModeScaleAspectFit;
    self.like_image.image = [UIImage imageNamed:@"礼物"];
    //[self.player.view addSubview:self.like_image];

    UIImageView *likes = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-210, 25, 25)];
    likes.image = [UIImage imageNamed:@"009551"];
    likes.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:likes];
        UILabel *like_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-45, screen_height-185, 40, 30)];
        like_Num.textAlignment = 1;
       // like_Num.textColor = [UIColor whiteColor];
        like_Num.text = @"0";
         like_Num.textColor = BASE_COLOR;
        like_Num.font = [UIFont systemFontOfSize:13];
        like_Num.tag = 1025;
        [self.view addSubview:like_Num];


    UIButton *like_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    like_Btn.frame = CGRectMake(screen_width-50, screen_height-160, 40, 40);
    [like_Btn setImage:[UIImage imageNamed:@"礼物"] forState:UIControlStateNormal];
    [like_Btn addTarget:self action:@selector(showgoods) forControlEvents:UIControlEventTouchUpInside];

    UIImageView *storeIcon = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-50, screen_height-270, 40, 40)];
    NSURL *storeUrl = [NSURL URLWithString:self.live_Detail[@"store"][@"logo"]];
    [storeIcon sd_setImageWithURL:storeUrl placeholderImage:[UIImage imageNamed:@"96"]];
    storeIcon.contentMode = UIViewContentModeScaleAspectFill;
    storeIcon.layer.cornerRadius = 20;
    storeIcon.layer.masksToBounds = 1;
    [self.view addSubview:storeIcon];

    }

    -(void)tapview{
    self.active_View.hidden = 1;
    self.filter_View.hidden = 1;
    }
    //绑定主播信息
    -(void)bindHostInfo{

    [self.view addSubview:self.hostInfoView];
    UIImageView *host_Icon = [[UIImageView alloc] init];
    host_Icon.frame = CGRectMake(0,0,40,40);
    host_Icon.layer.cornerRadius = 20;
    host_Icon.layer.masksToBounds = 1;
        host_Icon.contentMode = UIViewContentModeScaleAspectFill;
    NSDictionary *hostInfo = [XTool GetDefaultInfo:HOST_USER];
    NSURL *host_icons = [NSURL URLWithString:hostInfo[@"avatar"]];
    [host_Icon sd_setImageWithURL:host_icons placeholderImage:[UIImage imageNamed:@"logo"]];
    // host_Icon.image = [UIImage imageNamed:@"hosts"];
    [_hostInfoView addSubview:host_Icon];

    NSString *nick_Str = hostInfo[@"nickname"];
    CGFloat widths  =[XTool calculateRowWidth:nick_Str andHeight:15 andSize:12];
        if(widths>70){
            widths =70;
        }
    UILabel *nick_Lab = [[UILabel alloc] init];
    nick_Lab.frame = CGRectMake(45,5,widths,15);
    nick_Lab.text = hostInfo[@"nickname"];
    nick_Lab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12];
    nick_Lab.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    nick_Lab.textAlignment = NSTextAlignmentLeft;
    nick_Lab.alpha = 1;
    nick_Lab.numberOfLines = 0;
    [_hostInfoView addSubview:nick_Lab];

    UIImageView *level_Img = [[UIImageView alloc]initWithFrame:CGRectMake(45+5+widths, 5, 35, 15)];
    level_Img.image = [UIImage imageNamed:@"Group 20"];
    // level_Img.contentMode = UIViewContentModeScaleAspectFit;
    [_hostInfoView addSubview:level_Img];

    UILabel *leve_Lab = [[UILabel alloc]initWithFrame:CGRectMake(45+5+widths, 5, 30, 15)];
    leve_Lab.text = @"10";
    leve_Lab.textColor=[UIColor whiteColor];
    leve_Lab.font = [UIFont systemFontOfSize:11];
    leve_Lab.textAlignment = NSTextAlignmentRight;
    [_hostInfoView addSubview:leve_Lab];

    UILabel *room_id = [[UILabel alloc] init];
    room_id.frame = CGRectMake(45,20,140,20);
    room_id.text = [NSString stringWithFormat:@"房间号：%@ 粉丝：0",hostInfo[@"id"]];
    room_id.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:11];
    room_id.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    room_id.textAlignment = NSTextAlignmentLeft;
    room_id.alpha = 1;
    room_id.tag = 152;
    room_id.numberOfLines = 0;
    [_hostInfoView addSubview:room_id];


    }
    #pragma mark 获取主播的最新信息
    -(void)loadNewHostInfo{
    NSDictionary *params = @{@"ctrl":@"live_anchor",@"ac":@"member",@"op":@"member",@"ta":@"get_member"};
    [self weqPostHandle:params success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
    }

    #pragma mark 初始化推流界面和推流管理器session
    -(void)initSession{
    NSString *blive_Url =self.bdlive_Url;
    if(!blive_Url){
        blive_Url = @"rtmp://1111";
    }
     NSURL *url = [NSURL URLWithString:blive_Url];
    if(!self.session){
       self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
    }else{
        [self.session stopPreview];
        [self.session stop];
        self.session = nil;
        self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
    }
    self.session.delegate = self;
    self.session.view.frame = CGRectMake(0, 0, screen_width, screen_height);
    self.session.view.backgroundColor = RGBA(200, 200, 200, .8);
    [self.view insertSubview:self.session.view atIndex:0];
    [self.session startPreview];
    [self.session start];
    }
    #pragma mark 页面布局
    -(void)initSubViews{
    NSString *blive_Url =self.live_Url;
     // NSString *blive_Url =@"rtmp://bdlive.sharepanzer.com/bddemo/live_2_Host";
    if(!blive_Url){
        blive_Url = @"rtmp://1111";
    }

//        self.recordSession = [[BDCloudAVRecordSession alloc] initWithURL:[NSURL URLWithString:blive_Url]];
//        
//        // 设置事件回调
//        self.recordSession.delegate = self;
//        
//        // 添加预览窗口
//        [self.view addSubview:self.recordSession.view];
      //  [self.view addSubView:self.recordSession.view];
        AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        self.deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:videoDevice error:nil];
           _videoBufferQueue = dispatch_queue_create("video_buffer_handle_queue", NULL);
        self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
         _videoDataOutPut = [[AVCaptureVideoDataOutput alloc] init];//视频输出对象
        [_videoDataOutPut setSampleBufferDelegate:self queue:_videoBufferQueue];
        NSDictionary* setcapSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey,
                                        nil];
        _videoDataOutPut.videoSettings = setcapSettings;
 

    NSURL *url = [NSURL URLWithString:blive_Url];
    BDCloudAVCaptureSettings *capt = [[BDCloudAVCaptureSettings alloc]init];
    BDCloudAVVideoOutputSettings *VideoSetings = [[BDCloudAVVideoOutputSettings alloc]init];
        
    
    [VideoSetings setBitRate:3500000];
    
    BDCloudAVAudioOutputSettings *AudeoSetings = [[BDCloudAVAudioOutputSettings alloc]init];
        self.capturer = [[BDCloudAVCaptureOutput alloc]init];
        [self.capturer stop];
    self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
   // self.session = [[BDCloudAVLiveSession alloc]initWithURL:url captureConfig:capt videoSettings:VideoSetings audioSettings:nil];
    [self.session setMasterVolume:1.0];
    [self.session setVideoEnable:1];
    
    
    UserRole role = Host;
    self.session.view.frame = CGRectMake(0, 0, screen_width, screen_height);
    self.session.view.backgroundColor = RGBA(200, 200, 200, .8);
        
    //   [self.session connect];
    [self.view addSubview:self.session.view];
        [self.session setCameraPosition:AVCaptureDevicePositionBack];
    //  [self.session setVideoFrameRate:50];
    [self.session startPreview];//暂不开启
    // [self loadliveInfo];//直接播放
    [self.session setAutoFoucsMode];
    [self.session setVideoFrameRate:30];
    [self.session setAutoWhiteBalance];
    

    [self.session setAudioEnable:1];
    //  [self.session setMasterVolume:1.0];
    //  [self.session setMasterVolume:1];

    BDCloudAVMovieParameter *param = [[BDCloudAVMovieParameter alloc]init];
    param.videoSettings = VideoSetings;
        
        self.session.delegate = self;
    [self.session updateOutputParameter:param];
    [self bindHostInfo];
    //底部的活动规则
    UIView *botom_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-50, screen_width, 50)];
   // botom_View.backgroundColor = RGB(109, 109, 109);
        botom_View.backgroundColor = RGBA(0, 0, 0, .3);
    UILabel *rule_Lab = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, 0, screen_width-70, 50)];
    rule_Lab.textColor = [UIColor whiteColor];
    rule_Lab.text =@"本场规则：在随机变化的数字中，最先点中";
    rule_Lab.font = [UIFont systemFontOfSize:13];
    rule_Lab.tag = 1024;
    [botom_View addSubview:rule_Lab];

    UIImageView *guest_NumImage = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-60, 19, 12, 12)];
    guest_NumImage.image = [UIImage imageNamed:@"007551"];
    [botom_View addSubview:guest_NumImage];

    UILabel *guest_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, 0, 50, 50)];
    guest_Num.textColor = [UIColor whiteColor];
    guest_Num.text = @"0";
    guest_Num.font= [UIFont systemFontOfSize:12];
    [botom_View addSubview:guest_Num];
    guest_Num.tag = 1026;
    [self.view addSubview:botom_View];


    //抢购倒计时
    UILabel *time_text = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    time_text.text = @"直播未开始";
    time_text.textColor = [UIColor whiteColor];
    time_text.font = [UIFont systemFontOfSize:16];
    time_text.tag = 1028;
     [self.view addSubview:time_text];


    CGFloat timeDesY = screen_height-90;

    self.dayLb = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 110, 20)];

    self.dayLb.textColor = [UIColor whiteColor];
    self.dayLb.text = @"0";
    // self.dayLb.backgroundColor = BUTTON_COLOR;
    self.dayLb.font = [UIFont systemFontOfSize:18];
    self.dayLb.textAlignment = 1;
    self.dayLb.layer.cornerRadius = 5;
    self.dayLb.textAlignment = NSTextAlignmentLeft;
    self.dayLb.layer.masksToBounds = 1;
    [self.view addSubview:self.dayLb];
    self.dayLb.hidden = 1;



     self.time_lab1 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, timeDesY, time_Lab_width, time_Lab_height)];
    self.time_lab1.textColor = [UIColor blackColor];
    self.time_lab1.text = @"0";
    self.time_lab1.backgroundColor = BUTTON_COLOR;
    self.time_lab1.font = [UIFont systemFontOfSize:25];
    self.time_lab1.textAlignment = 1;
    self.time_lab1.layer.cornerRadius = 5;
    self.time_lab1.layer.masksToBounds = 1;
    [self.view addSubview:self.time_lab1];

    self.time_lab2 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+10-5, screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab2.textColor = [UIColor blackColor];
    self.time_lab2.text = @"0";
    self.time_lab2.backgroundColor = BUTTON_COLOR;
    self.time_lab2.font = [UIFont systemFontOfSize:25];
    self.time_lab2.textAlignment = 1;
    self.time_lab2.layer.cornerRadius = 5;
    self.time_lab2.layer.masksToBounds = 1;
    [self.view addSubview:self.time_lab2];

    UILabel *mao = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+10, screen_height-90, 5, time_Lab_height)];
    mao.text = @":";
    mao.textColor = [UIColor blackColor];
    mao.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:mao];

    self.time_lab3 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+20, screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab3.textColor = [UIColor blackColor];
    self.time_lab3.text = @"0";
    self.time_lab3.backgroundColor = BUTTON_COLOR;
    self.time_lab3.font = [UIFont systemFontOfSize:25];
    self.time_lab3.textAlignment = 1;
    self.time_lab3.layer.cornerRadius = 5;
    self.time_lab3.layer.masksToBounds = 1;
    [self.view addSubview:self.time_lab3];

    self.time_lab4 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*3+30-5, screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab4.textColor = [UIColor blackColor];
    self.time_lab4.text = @"0";
    self.time_lab4.backgroundColor = BUTTON_COLOR;
    self.time_lab4.font = [UIFont systemFontOfSize:25];
    self.time_lab4.textAlignment = 1;
    self.time_lab4.layer.cornerRadius = 5;
    self.time_lab4.layer.masksToBounds = 1;
    [self.view addSubview:self.time_lab4];




    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    share_Btn.frame = CGRectMake(screen_width-50, screen_height-100, 40, 40);
    [share_Btn setImage:[UIImage imageNamed:@"filters"] forState:UIControlStateNormal];
    [share_Btn addTarget:self action:@selector(showfilter) forControlEvents:UIControlEventTouchUpInside];
    share_Btn.tag= 1101;
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.view addSubview:share_Btn];
    //preplay
    UIButton *start = [UIButton buttonWithType:UIButtonTypeCustom];
    start.frame = CGRectMake(screen_width-50, screen_height-160, 40, 40);
    [start setImage:[UIImage imageNamed:@"preplay"] forState:UIControlStateNormal];
    [start addTarget:self action:@selector(showDiagAlert) forControlEvents:UIControlEventTouchUpInside];
    start.tag = 1102;
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.view addSubview:start];

        
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.frame = CGRectMake(screen_width/2-30, screen_height-120, 60, 30);
//        [btn setTitle:@"检测" forState:UIControlStateNormal];
//        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//        [btn addTarget:self action:@selector(startRecord) forControlEvents:UIControlEventTouchDown];
//        [btn addTarget:self action:@selector(stopRecord) forControlEvents:UIControlEventTouchUpInside];
//        btn.tag = 2225;
//        [self.view addSubview:btn];

    //右边的点赞和分享元素
    //    UIImageView *share_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-100, 25, 25)];
    //    share_img.image = [UIImage imageNamed:@"分享按钮551"];
    //    share_img.contentMode = UIViewContentModeScaleAspectFit;
    //    [self.view addSubview:share_img];
    //
    //
    //    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    share_Btn.frame = CGRectMake(screen_width-60, screen_height-110, 50, 50);
    //    [share_Btn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    //   [self.view addSubview:share_Btn];
    //
    //
    //    self.like_image = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-160, 30, 30)];
    //    self.like_image.contentMode = UIViewContentModeScaleAspectFit;
    //    self.like_image.image = [UIImage imageNamed:@"009551"];
    //    [self.view addSubview:self.like_image];
    //
    //    UILabel *like_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-130, 30, 20)];
    //    like_Num.textAlignment = 1;
    //    like_Num.textColor = [UIColor whiteColor];
    //    like_Num.text = @"10w";
    //    like_Num.font = [UIFont systemFontOfSize:13];
    //    like_Num.tag = 1025;
    //    [self.view addSubview:like_Num];
    //
    //
    //    UIButton *like_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    like_Btn.frame = CGRectMake(screen_width-60, screen_height-170, 50, 50);
    //    [like_Btn addTarget:self action:@selector(like) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:like_Btn];
    [self.view addSubview:self.filter_View];
    self.filter_View.hidden = 1;


    //右上角关闭按钮
    NSInteger margin_Top = KISIphoneX?55:30;
    UIImageView *close_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-30, margin_Top+15, 30, 30)];
    close_img.image = [UIImage imageNamed:@"closesss"];
    // /   [self.view addSubview:close_img];
    UIButton *close_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    close_btn.frame = CGRectMake(screen_width-50, margin_Top, 50, 50);
     [close_btn setImage:[UIImage imageNamed:@"closesss"] forState:UIControlStateNormal];
    //[close_btn setTitle:@"关闭" forState:UIControlStateNormal];
    [close_btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [close_btn addTarget:self action:@selector(close_Live) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:close_btn];

    //  NSInteger margin_Top = KISIphoneX?55:30;
    UIImageView *close_img1 = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-80, margin_Top+15, 30, 30)];
    close_img1.image = [UIImage imageNamed:@"camerap"];
    //  [self.view addSubview:close_img1];
    UIButton *close_btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    close_btn1.frame = CGRectMake(screen_width-110, margin_Top, 50, 50);
    [close_btn1 setImage:[UIImage imageNamed:@"camerap"] forState:UIControlStateNormal];
    //[close_btn setTitle:@"关闭" forState:UIControlStateNormal];
    [close_btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [close_btn1 addTarget:self action:@selector(camerapositions) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:close_btn1];
 //       [self.session.view addSubview:close_btn1];
    dispatch_async(dispatch_get_main_queue(), ^{
      
    });

    }
    -(void)showActiveTime:(BOOL)show{
    //  self.isstart = 1;
    //self.isrobing = 0;
    // CGFloat width = show?140:0;
    CGFloat width = 0;
    [UIView animateWithDuration:0.5 animations:^{
        
        self.activeTimeView.frame = CGRectMake(margin_left+time_Lab_width*3+30-5+30, screen_height-85, width, 20);
    }];
    }
    -(void)showActiveTimes{
        self.isrobing = 1;
    CGFloat width =140;
    [UIView animateWithDuration:0.5 animations:^{
        self.activeTimeView.frame = CGRectMake(margin_left+time_Lab_width*3+30-5+30, screen_height-85, width, 20);
    }];
    }
    #pragma mark 切换摄像头
    -(void)camerapositions{
    self.camerapostion= !self.camerapostion;
    if(self.camerapostion==1){
    [self.session setCameraPosition:AVCaptureDevicePositionBack];
    
    }else{
         [self.session setCameraPosition:AVCaptureDevicePositionFront];
    
//       AVCaptureConnection *connection = [self.videoDataOutPut connectionWithMediaType:AVMediaTypeVideo];
//        NSLog(@"设备输出%@",connection);
//        connection.videoOrientation = AVCaptureVideoOrientationPortrait;
//        connection.videoMirrored = 0;
    }
}
    #pragma mark 开启l美颜调节器
    -(void)showfilter{
    [self.view bringSubviewToFront:self.filter_View];
    self.filter_View.hidden = 0;
    }
    - (void)viewDidLoad {
    [super viewDidLoad];
        [self checkMike];
  //  [self checkmike];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeExit:)
                                                 name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.

    [self initSubViews];
    self.openDm = 1;
    self.Dampage = 1;
    self.camerapostion = 1;
        
    //
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapview)];
    [self.view addGestureRecognizer:tapView];
    }
    #pragma mark 检测麦克风
    -(void)checkmike{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
            //没有询问是否开启麦克风
            
            break;
        case AVAuthorizationStatusRestricted:
            //未授权，家长限制
            
            break;
        case AVAuthorizationStatusDenied:
            //玩家未授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
              
            }];
            break;
        case AVAuthorizationStatusAuthorized:
            //玩家授权
            
            break;
        default:
            break;
    }


    }
    -(void)homeExit:(NSNotification *)no{
    if(_socket){
      //  [_socket close];
    }
    }
    #pragma mark 直播时间已到，关闭直播间
    -(void)timeOut{
    EndLiveViewController *vc = [[EndLiveViewController alloc]init];
    vc.live_Id = self.live_id;
    [self pushSecondVC:vc];
    }
    #pragma mark 主播中途关闭直播界面
    //主播中途关闭直播界面
    -(void)close_Live{
    if(self.is_start==0){
        [self.session stopPreview];
        self.session = nil;
       // [_socket close];
    [self.navigationController popViewControllerAnimated:0];
    }else{
    DXAlertView *alert = [[DXAlertView alloc]initWithTitle:@"提示" message:@"确认关闭直播间" cancelBtnTitle:@"取消" otherBtnTitle:@"下播"];
    alert.tag = 6;
    alert.delegate = self;
    [alert show];
    }

    }
    #pragma mark socket 发送主播下播指令
    -(void)sendCloseNoti:(NSInteger)type{
    //主播下播97下播，96退出
    NSDictionary *param = @{@"id":self.live_id,@"u_type":@"2",@"room_no":self.roomNum};
    NSString *str = [self dictiontoJson:param andCode:type];
    [self.socket writeString:str];
    }
    -(void)dxAlertView:(DXAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if(buttonIndex!=0){
        [self requestClose];
        if(alertView.tag==5){
            //直播时间已到
            
           // [self sendCloseNoti:96];
        }
        else{
            //中途退出
            [self sendCloseNoti:97];
        }
        
        if(self.session){
            [self.session stopPreview];
            [self.session stop];
            self.session = nil;
        }
        if([self.socket isConnected]==1){
             [self.socket disconnect];
        }
        [self.navigationController popViewControllerAnimated:1];
       
        
        if(self.timer){
            dispatch_cancel(self.timer);
        }

    }else{
        
    }
    }
    #pragma mark 向服务器发起下拨请求
    -(void)requestClose{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_HUD];
    _HUD.label.text = @"直播数据关闭中";
    //细节文字
    _HUD.detailsLabel.text = @"请耐心等待";
    NSDictionary *params = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"downlive",@"act_id":self.live_id};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            [self.HUD removeFromSuperview];
    }
    } failure:^(NSError *error) {
        
    }];
    }
    //分享
    -(void)shareAction{

    }
    //点赞
    -(void)like{
    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"zan",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        
        if(response){
            self.like_image.image = [UIImage imageNamed:@"009551"];
        }
    } failure:^(NSError *error) {
        
    }];
    }

    //用户点击随机数进行抽奖
    -(void)clickRandom:(UIButton *)btn{


    NSInteger rand_Nums = [btn.titleLabel.text integerValue];
    if(rand_Nums==self.rewad_Num){
        // [WToast showWithText:@"恭喜你中奖了"];
        NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"rob",@"act_id":self.live_id};
        [self weqPostHandle:param success:^(id response) {
            
        } failure:^(NSError *error) {
            
        }];
    }

    }

    -(void)randoms{
    int y =0 +  (arc4random() % 10);
    [self.random_Btn setTitle:[NSString stringWithFormat:@"%d",y] forState:UIControlStateNormal];
    }
#pragma mark 开始前先检测麦克风是否正常
-(void)checkMike{
    self.Audionsession = [AVAudioSession sharedInstance];
    [self.Audionsession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [self.Audionsession setActive:YES error:nil];
    //录音设置
    NSMutableDictionary * recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式
    [recordSetting  setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率（HZ）
    [recordSetting setValue:[NSNumber numberWithFloat:4000] forKey:AVSampleRateKey];
    //录音通道数
    [recordSetting setValue:[NSNumber  numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数
    [recordSetting  setValue:[NSNumber numberWithInt:8] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting  setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    //获取沙盒路径 作为存储录音文件的路径
    NSString * strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"path = %@",strUrl);
    //创建url
    NSURL * url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/voice.aac",strUrl]];
    self.urlPlay = url;
    NSError * error ;
    //初始化AVAudioRecorder
    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量监测
    self.recorder.meteringEnabled = YES;
    self.recorder.delegate = self;
    if(error){
        NSLog(@"创建录音对象时发生错误，错误信息：%@",error.localizedDescription);
    }
    


}
//-(void)startRecord{
//     [self.Audionsession setCategory:AVAudioSessionCategoryRecord error:nil];
//    [self.recorder record];
//    NSLog(@"开始录音");
//}
//-(void)stopRecord{
//    [self.recorder stop];
//    [self.Audionsession setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [self.Audionsession setActive:YES error:nil];
//     NSLog(@"结束录音===%@",_urlPlay);
//   self.Audioplayer = [[AVAudioPlayer alloc]initWithContentsOfURL:self.urlPlay error:nil];
//
//    [self.Audioplayer play];
//
//}
//- (AVPlayer *)Audioplayer {
////    if (_Audioplayer == nil) {
////        _Audioplayer = [[AVAudioPlayer alloc] init];
////        _Audioplayer.volume = 1.0; // 默认最大音量
////    }
////    return _Audioplayer;
//}


    - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

    @end
